<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue'
import config from '@/config'
import * as Cesium from 'cesium'
import 'public/libs/cesium/Widgets/widgets.css'
import MapIcon from './components/MapIcon/index.vue'
import ModelPicker from './components/ModelPicker/index.vue'
import { LayerModel, MapTypeModel } from './types'

//地图容器
const viewerRef = ref<HTMLDivElement>()
//viewer
const viewer = ref<null | Cesium.Viewer>(null)
//2d/3d模式
const mapModel = ref<Cesium.SceneMode>(Cesium.SceneMode.SCENE2D)
//图层模式
const layerModel = ref<LayerModel>(LayerModel.VEC_BASIC_LAYER)
//地图类型
const mapType = ref<MapTypeModel>(MapTypeModel.GAO_DE) 
//设置全局cesium的base_url
window.CESIUM_BASE_URL = config.BASE_URL
//设置token
Cesium.Ion.defaultAccessToken = config.TOKEN

//初始化viewer
const initMap = () => {
    //配置viewer
    viewer.value = new Cesium.Viewer(viewerRef.value as HTMLDivElement, {
        animation: false,
        navigationHelpButton: false,
        baseLayerPicker: false,
        fullscreenButton: false,
        infoBox: false,
        homeButton: false,
        geocoder: false,
        selectionIndicator: false,
        sceneModePicker: false,
        timeline: false,
        navigationInstructionsInitiallyVisible: false,
        sceneMode: mapModel.value,
    })

    //初始化图层
    selectMapTypeLayer()

    //隐藏自带icon
    //@ts-ignore
    viewer.value.cesiumWidget.creditContainer.style.display = 'none'
    //切换到中国的位置
    viewer.value.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(103.84, 31.15, 12850000),
        orientation: {
            heading :  Cesium.Math.toRadians(348.4202942851978),
            pitch : Cesium.Math.toRadians(-89.74026687972041),
            roll : Cesium.Math.toRadians(0)
        },
        duration: 0
    })
}

//切换天地图图层
const changeMapWorldLayer = (model: LayerModel) => {
    //设置底图图层
    let imgLayer = new Cesium.WebMapTileServiceImageryProvider({
        url: `${config.MAP_WORLD_URL}/${model === LayerModel.VEC_BASIC_LAYER ? 'vec_w' : 'img_w'}/wmts?tk=${config.MAP_WORLD_TOKEN}`,
        layer: `${model === LayerModel.VEC_BASIC_LAYER ? 'vec' : 'img'}`,
        style: 'default',
        format: 'tiles',
        tileMatrixSetID: "w",
    })
    //设置注记图层
    let textLayer = new Cesium.WebMapTileServiceImageryProvider({
        url: `${config.MAP_WORLD_URL}/${model === LayerModel.VEC_BASIC_LAYER ? 'cva_w' :  'cia_w'}/wmts?tk=${config.MAP_WORLD_TOKEN}`,
        layer: `${model === LayerModel.VEC_BASIC_LAYER ? 'cva' : 'cia'}`,
        style: 'default',
        format: 'tiles',
        tileMatrixSetID: "w",
    })
    //添加图层
    viewer.value?.imageryLayers.addImageryProvider(imgLayer)
    viewer.value?.imageryLayers.addImageryProvider(textLayer)
}

//切换高德图层
const changeGaoDeLayer = (model: LayerModel) => {
    //判断是矢量图还是影像图
    let isVec = model === LayerModel.VEC_BASIC_LAYER
    let url = isVec 
    ? 'http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}' : 'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}'
    let imgLayer = new Cesium.UrlTemplateImageryProvider({
        url,
        maximumLevel: 18,
        minimumLevel: 4,
        credit: 'Amap'
    })
    viewer.value?.imageryLayers.addImageryProvider(imgLayer)
    //如果是影像图需要另外添加注记图层
    if(!isVec) {
        let textLayer = new Cesium.UrlTemplateImageryProvider({
            url: 'http://webst02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8',
            maximumLevel: 18,
            minimumLevel: 4,
        })
        viewer.value?.imageryLayers.addImageryProvider(textLayer)
    }
}

//切换2d/3d
const handleMapModel = (model: Cesium.SceneMode) =>{
    mapModel.value = model
    if(viewer.value !== null) {
        viewer.value!.scene.mode = mapModel.value 
    }
}

//切换图层
const handleLayerModel = (model: LayerModel, type: MapTypeModel) => {
    layerModel.value = model
    mapType.value = type
    selectMapTypeLayer()
}

//根据地图类型选择切换图层方法
const selectMapTypeLayer = () => {
    //先去除所有图层
    viewer.value?.imageryLayers.removeAll(true)
    switch(mapType.value) {
        case MapTypeModel.MAP_WORLD:
            changeMapWorldLayer(layerModel.value)
            break
        case MapTypeModel.GAO_DE:
            changeGaoDeLayer(layerModel.value)
            break
    }
}

onMounted(() => {
    initMap()
})

onUnmounted(() =>{
    //页面卸载时销毁viewer
    viewer.value?.destroy()
})
</script>

<template>
    <div class="container" ref="viewerRef">
       <MapIcon title="" url="../../../../assets/logo.png" />
       <ModelPicker :map-type="mapType" :map-model="mapModel" :layer-model="layerModel" @handle-map-model="handleMapModel" 
       @handle-layer-model="handleLayerModel" />
    </div>
</template>


<style lang="css" scoped>
.container {
    width: 100%;
    height: 100vh;
    position: relative;
}
</style>